package net.yunxinyong.cec.service.impl;

import net.yunxinyong.cec.entity.EcnomicInventory;
import net.yunxinyong.cec.entity.EcnomicInventoryExample;
import net.yunxinyong.cec.entity.InventorFile;
import net.yunxinyong.cec.mapper.EcnomicInventoryMapper;
import net.yunxinyong.cec.mapper.InventorFileMapper;
import net.yunxinyong.cec.service.PassportService;
import net.yunxinyong.cec.utils.CecException;
import net.yunxinyong.cec.utils.ListUtils;
import net.yunxinyong.cec.vo.EnterVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class PassportServiceImpl implements PassportService {

    @Autowired
    private EcnomicInventoryMapper ecnomicInventoryMapper;
    @Autowired
    private InventorFileMapper inventorFileMapper;
    @Override
    public EcnomicInventory enter(EnterVo enterVo) {
        EcnomicInventoryExample ecnomicBrancesExample = new EcnomicInventoryExample();
        ecnomicBrancesExample.createCriteria().andUnitDetailedNameEqualTo(enterVo.getName());
        List<EcnomicInventory> ecnomicInventories = ecnomicInventoryMapper.selectByExample(ecnomicBrancesExample);
        if (!ListUtils.isEmpty(ecnomicInventories)){
            return ecnomicInventories.get(0);
        }else {
            return null;
        }
    }

    @Override
    public EcnomicInventory register(EnterVo enterVo, String fileName) {
        //判断企业是否已存在
        EcnomicInventoryExample ecnomicInventoryExample = new EcnomicInventoryExample();
        ecnomicInventoryExample.createCriteria().andUnitDetailedNameEqualTo(enterVo.getName());
        List<EcnomicInventory> ecnomicInventories = ecnomicInventoryMapper.selectByExample(ecnomicInventoryExample);
        if (!ListUtils.isEmpty(ecnomicInventories)){
            return null;
        }
        //添加企业
        EcnomicInventory ecnomicInventory = new EcnomicInventory();
        ecnomicInventory.setUnitDetailedName(enterVo.getName());
        ecnomicInventory.setSocialCreditCode(enterVo.getSocialCreditCode());
        ecnomicInventory.setOrganizationCode(enterVo.getOrganizationCode());
        ecnomicInventory.setUiteStatus(0);
        ecnomicInventory.setCreatetime(new Date());
        int insertSelective = ecnomicInventoryMapper.insertSelective(ecnomicInventory);
        if (insertSelective > 0){
            //添加图片记录
            InventorFile inventorFile = new InventorFile();
            inventorFile.setCreateTime(new Date());
            inventorFile.setFileName(fileName);
            inventorFile.setCreateTime(new Date());
            inventorFile.setInventoryId(ecnomicInventory.getId());
            int i = inventorFileMapper.insertSelective(inventorFile);
            if (i>0){
                return ecnomicInventory;
            }else {
                return null;
            }
        }else {
            return null;
        }
    }
}
